#!/bin/bash

# 设置环境变量
export sastUrl="http://192.168.172.131"
export sastToken="sast_1awyrzi7y8j152fgult3j6x31fxxig5n"
export appType="1"
export projectId=" "
export appRuleList='[{"languageType":1,"languageName":"Java/Android/JSP","ruleIdTmpId":"392612833919202","ruleTmpName":"[Java] 缺陷检测推荐模板","ruleTmpType":"2"}]'
export sourceCodeType="source_code_file"
export buildCommands=""
export whiteMethodsSetsId="0"
export fileFilterSetsId="0"
export taskSourceType="3009"
export detectionType="1"
export scanningMode="1"
export description=" "
export ENABLE_QUALITY_GATE="0"
export TOTAL_HIGH_COUNT="0"
export TOTAL_MIDDLE_COUNT="0"
export TOTAL_LOW_COUNT="0"
export TOTAL_SUPER_COUNT="0"
export BY_PASS="0"
export BY_PASS_ERROR_FLAG="0"
export BY_PASS_TIMEOUT_MINUTES="15"
export customAppName="应用名称"
export customReportName="报告名称"

#apt-get update && apt-get install -y zip jq
#yum install -y zip jq
if [ "${sourceCodeType}" == "intermediate_file" ]; then
  ${buildCommands}
  mv xmirror-compilte.zip ${customAppName}.zip
else
  zip -r ${customAppName}.zip .
fi
# 获取应用id
response=$(curl --request GET --url "${sastUrl}/sast/api-v1/open-api/app/generate/id" --header "Sast-Token: ${sastToken}" -k)
echo "Response: $response"
appId=$(echo "$response" | jq -r '.data')
echo "appId: $appId"
# 提交sast任务
curl_command="curl --request POST -k --url ${sastUrl}/sast/api-v1/open-api/app/saveTask \
    --header 'Sast-Token: ${sastToken}' \
    --header 'content-type: multipart/form-data' \
    --form \"file=@${customAppName}.zip\" \
    --form 'addTaskJson={
      \"repositoryType\": 0,
      \"appType\": ${appType},
      \"projectId\": ${projectId},
      \"appId\": ${appId},
      \"appName\": \"${customAppName}\",
      \"appRuleList\": ${appRuleList},
      \"whiteMethodsSetsId\": ${whiteMethodsSetsId},
      \"fileFilterSetsId\": ${fileFilterSetsId},
      \"taskSourceType\": ${taskSourceType},
      \"detectionType\": ${detectionType},
      \"scanningMode\": ${scanningMode},
      \"description\": \"${description}\"
    }'"
echo "$curl_command"
response=$(eval "$curl_command")
code=$(echo "$response" | jq -r --raw-output '.code')
if [ "$code" -ne 0 ] && [ "${BY_PASS_ERROR_FLAG}" = 1 ]; then
  exit 0
fi
# 轮询SAST任务结果
status=0
taskId=0
start_time=$(date +%s)
while [ $status -ne 3 ]; do
  current_time=$(date +%s)
  elapsed=$((current_time - start_time))
  if [ "$BY_PASS" == 1 ] && [ $(($elapsed / 60)) -ge $BY_PASS_TIMEOUT_MINUTES ]; then
    echo "Bypass enabled and time limit exceeded. Exiting..."
    break
  fi
  sleep 30
  response=$(curl --request GET --url "${sastUrl}/sast/api-v1/open-api/defect/jenkins/result?appId=${appId}" -k --header "Sast-Token: ${sastToken}")
  echo "Response: $response"
  status=$(echo "$response" | jq -r '.data.status')
  echo "Current task status: $status"
  if [ "$status" = "0" ] && [ "${BY_PASS_ERROR_FLAG}" = 1 ]; then
    exit 1
  fi
  taskId=$(echo "$response" | jq -r '.data.taskId')
  echo "Current task Id: $taskId"
done

reportResponse=$(curl --request GET -k --url "${sastUrl}/sast/api-v1/open-api/defect/blue/generate/report?reportType=1&taskId=${taskId}&reportName=${customReportName}&appId=${appId}" --header "Sast-Token: ${sastToken}")
reportId=$(echo "$reportResponse" | jq -r '.data')
echo "Report ID: $reportId"

status=0
while [ $status -ne 2 ]; do
  sleep 30
  statusResponse=$(curl --request GET -k --url "${sastUrl}/sast/api-v1/open-api/defect/blue/generate/report/status?reportId=${reportId}" -H "Sast-Token: ${sastToken}")
  status=$(echo "$statusResponse" | jq -r '.data.status')
  echo "Current report status: $status"
done

wget --no-check-certificate --header="Sast-Token: ${sastToken}" "${sastUrl}/sast/api-v1/open-api/defect/blue/download/report?reportId=${reportId}" -O sast_report.pdf

if [ "$ENABLE_QUALITY_GATE" == 1 ]; then
  echo $response
  highCount=$(echo "$response" | jq '.data.openJenkinsFlawInfoMap | map(.highCount) | add')
  middleCount=$(echo "$response" | jq '.data.openJenkinsFlawInfoMap | map(.middleCount) | add')
  lowCount=$(echo "$response" | jq '.data.openJenkinsFlawInfoMap | map(.lowCount) | add')
  superCount=$(echo "$response" | jq '.data.openJenkinsFlawInfoMap | map(.superCount) | add')

  echo "Total High Count: $highCount"
  echo "Total Middle Count: $middleCount"
  echo "Total Low Count: $lowCount"
  echo "Total Super Count: $superCount"

  if [ "$highCount" -gt "$TOTAL_HIGH_COUNT" ] || [ "$middleCount" -gt "$TOTAL_MIDDLE_COUNT" ] || [ "$lowCount" -gt "$TOTAL_LOW_COUNT" ] || [ "$superCount" -gt "$TOTAL_SUPER_COUNT" ]; then
    echo "One or more flaw counts exceed the maximum limit. Failing the build."
    exit 1
  else
    echo "All flaw counts are within the acceptable limits."
  fi
fi